package campshop.daos;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import campshop.models.OrderInfo;
public class OrderInfoDao extends JdbcDaoSupport{

	public long addOrderInfo(OrderInfo oi)
	{
		String sql = "insert into " +
				"tbl_order_info (cs_uId, oi_uState, gi_uGoodsId, oi_uGoodsNum, oi_dCreateDate, oi_fMoney)" +
				" values (?, ?, ?, ?, ?, ?)";
		if(super.getJdbcTemplate().update(sql, oi.getuUserId(), oi.getuState(), oi.getuGoodsId(), oi.getuGoodsNum(), 
				oi.getdCreateDate(), oi.getfMoney())>0){
			return super.getJdbcTemplate().queryForInt("select max(oi_uId) from tbl_order_info");
		}else return 0L;
	}
	
	public boolean delOrderInfo(long uId)
	{
		String sql = "delete from tbl_order_info where oi_uId = ?";
		if(super.getJdbcTemplate().update(sql, uId)>0) return true;
		return false;
	}
	
	public boolean updateOrderInfo(OrderInfo oi) {
		String sql="update tbl_order_info " +
				"set cs_uId=?, oi_uState=?, gi_uGoodsId=?, oi_uGoodsNum=?, oi_dCreateDate=?, oi_fMoney=? " +
				"where oi_uId = ?";
		if(super.getJdbcTemplate().update(sql, oi.getuUserId(), oi.getuState(), oi.getuGoodsId(), oi.getuGoodsNum(), 
				oi.getdCreateDate(), oi.getfMoney(), oi.getuOrderId())>0){
			return true;
		}else return false;
	}
	
	//一个订单对应可以对应多种商品，所以一个完整订单，是由多种商品拼接而成的
	public List<OrderInfo> getOrderInfo(long uId)
	{
		String sql = "select * from tbl_order_info where oi_uId=" + uId;
		return super.getJdbcTemplate().query(sql, new OrderInfoRowMapper());
	}
	class OrderInfoRowMapper implements RowMapper<OrderInfo>{
		@Override
		public OrderInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
			OrderInfo oi = new OrderInfo();
			oi.setuOrderId(rs.getLong("oi_uId"));
			oi.setuUserId(rs.getLong("cs_uId"));
			oi.setuState(rs.getInt("oi_uState"));
			oi.setuGoodsId(rs.getLong("gi_uGoodsId"));
			oi.setuGoodsNum(rs.getLong("oi_uGoodsNum"));
			oi.setdCreateDate(rs.getDate("oi_dCreateDate"));
			oi.setfMoney(rs.getFloat("oi_fMoney"));
			return oi;
		}	
	}
}